package com.rupeng.hibernate.cfg;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

public class ConfigHelper {

	public static InputStream parsePOMapping(String resource) {
		String stripped = resource.startsWith("/") ?
				resource.substring(1) : resource;

		InputStream stream = null;
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader!=null) {
			stream = classLoader.getResourceAsStream(stripped);
		}
		
		return stream;
	}
	
	public static org.dom4j.Document parsePOMapping(InputStream stream) {
		org.dom4j.Document doc = null;
		
		SAXReader reader = new SAXReader();
	    try {
			doc = reader.read(new InputSource(stream));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return doc;
	}
	
	public static void parsePOMapping(org.dom4j.Document doc, Properties properties) {
		Element sfNode = doc.getRootElement().element("class");
		String name = sfNode.attributeValue("name");
		String objName = name.substring(name.lastIndexOf(".") + 1);
		addIdElement(sfNode, properties);
		
		properties.setProperty(name, objName);
//System.out.println("class:" + name);
		addProperties(sfNode, properties);
	}
	
	private static void addIdElement(Element element, Properties properties) {
		Element id = element.element("id");
		String name = id.attributeValue("name");
		String value = element.getText().trim();
		
		properties.setProperty(name, name);
//System.out.println( name + " | " + value );
		addProperties(element, properties);
	}
	
	private static void addProperties(Element parent, Properties properties) {
		Iterator iter = parent.elementIterator("property");
		
		while (iter.hasNext()) {
			Element node = (Element) iter.next();
			String name = node.attributeValue("name");
			String value = node.getText().trim();

			properties.setProperty(name, name);
//System.out.println( name + " | " + value );
		}
	}
}
